package com.water_work_form.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.water_work_form.entity.*;
import com.water_work_form.entity.dto.DrugTestDTO;
import com.water_work_form.mapper.*;
import com.water_work_form.mapper.dto.DrugTestMapper;
import com.water_work_form.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 余繁
 */
@Service
public class RecordDrugTestServiceImpl extends ServiceImpl<RecordDrugTestMapper, RecordDrugTest> implements RecordDrugTestService {

    @Autowired
    RecordDrugTestMapper recordDrugTestMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Autowired
    BasicFormulaMapper basicFormulaMapper;

    @Autowired
    BasicMedicalMapper basicMedicalMapper;

    @Autowired
    DrugTestMapper drugTestMapper;

    @Autowired
    BasicRestrictionMapper basicRestrictionMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;



    /**
     * 混凝-进厂药剂检测记录 项目查询
     * @param type 项目类型（type） 若非空则进行匹配查询（基本上不会为空，前端给定默认值）
     * @param status 项目状态（status） 若非空进行匹配查询
     * @param startSampleDate 取样日期（sample_date）范围查询开始日期 若非空查询sample_date大于startSampleDate的数据
     * @param endSampleDate 取样日期（sample_date）范围查询结束日期 若非空查询sample_date小于endSampleDate的数据
     * @param current 分页 当前页
     * @param size 分页 每页数据量
     * @return 返回对应数据
     */
    @Override
    public IPage<RecordDrugTest> selectRecordDrugTest(String type, String status, String startSampleDate, String endSampleDate, Integer current, Integer size){
        QueryWrapper<RecordDrugTest> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", type);
        if(!status.isEmpty()){
            queryWrapper.eq("status", status);
        }
        if(!startSampleDate.isEmpty() && !endSampleDate.isEmpty()){
            queryWrapper.ge("sample_date", startSampleDate).le("sample_date", endSampleDate);
        }
        queryWrapper.orderByAsc("status", "sample_date", "sample_time");
        IPage<RecordDrugTest> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    /**
     * 混凝-进厂药剂检测记录  基础表数据查询
     * @param type 项目类型（type） formula表name，medical表name，restriction表name
     * @param name form表name
     * @return 返回相应数据 表名为键名
     */
    @Override
    public Map<String, Object> selectBasicDrugTest(String type, String name) {
        Map<String, Object> map = new HashMap<>();
        map.put("form", basicFormMapper.getOneByName(name));
        QueryWrapper<DrugTestDTO> queryWrapper = new QueryWrapper<>(); // 获取基础表数据
        queryWrapper.eq("a.name", type).select("a.name", "a.formula_content", "a.formula_description", "b.standard_name", "b.concentration",
                "b.certificate_no", "b.effective_date", "c.standard_basis");
        DrugTestDTO drugTestDTO = drugTestMapper.selectOne(queryWrapper);
        Map<String, Object> formula = new HashMap<>(); // 数据组装
        formula.put("formulaContent", drugTestDTO.getFormulaContent());
        formula.put("formulaDescription", drugTestDTO.getFormulaDescription());
        Map<String, Object> restriction = new HashMap<>();
        restriction.put("name", drugTestDTO.getName());
        restriction.put("standardBasis", drugTestDTO.getStandardBasis());
        Map<String, Object> medical = new HashMap<>();
        medical.put("standardName", drugTestDTO.getStandardName());
        medical.put("concentration", drugTestDTO.getConcentration());
        medical.put("certificateNo", drugTestDTO.getCertificateNo());
        medical.put("effectiveDate", drugTestDTO.getEffectiveDate());
        map.put("formula", formula);
        map.put("restriction", restriction);
        map.put("medical", medical);
        return map;
    }

    /**
     * 记录——进厂药剂检测记录 列表数据导出
     * @param recordDrugTestList 需要导出的数据列表
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordDrugTest(List<RecordDrugTest> recordDrugTestList, String restrictionString, String formulaContentString, String formulaDescriptionString,
                                       String medicalString) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        List<Map<String,Object>> formatList = new ArrayList<>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat datetimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        // 使用map方法获取对象的时间字段，并格式化
        List<String> formatSampleDate  = recordDrugTestList.stream()
                .map(recordDrugTest -> dateFormat.format(recordDrugTest.getSampleDate()))
                .collect(Collectors.toList());
        List<String> formatCheckTime  = recordDrugTestList.stream()
                .map(recordDrugTest -> datetimeFormat.format(recordDrugTest.getCheckTime()))
                .collect(Collectors.toList());
        for (int i = 0;i < recordDrugTestList.size();i++){
            Map<String,Object> map = new HashMap<>();
            map.put("list",recordDrugTestList.get(i));
            map.put("sampleDate",formatSampleDate.get(i));
            map.put("checkTime",formatCheckTime.get(i));
            formatList.add(map);
        }
        List<String> descriptionList= Arrays.asList(formulaDescriptionString.split("；"));
        List<Map<String,Object>> formulaDescriptionList = new ArrayList<Map<String,Object>>();
        for (int i = 0;i < descriptionList.size();i++){
            Map<String,Object> map = new HashMap<>();
            map.put("index",i);
            map.put("formulaDescription",descriptionList.get(i));
            formulaDescriptionList.add(map);
        }
        JSONObject restriction =  JSON.parseObject(restrictionString);
        JSONObject formulaContent =  JSON.parseObject(formulaContentString);
        JSONObject medical =  JSON.parseObject(medicalString);
        String img = "http://localhost:88/file/" + formulaContent.get("url");
        data.put("lists",formatList);
        data.put("restriction",restriction);
        data.put("formulaContent", Pictures.ofUrl(img)
                .size(200, 50).create());
        data.put("formulaDescriptionList",formulaDescriptionList);
        data.put("medical",medical);
        System.out.println(data.get("formulaContent"));
        // 插件列表,可以去官网查看，有列循环，还有行循环，这里是行循环实例
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        //这里可以指定一个config类，用来指定一些规则，也可以改变模板中{{}}的这种格式
        Configure config = Configure.builder()
                .bind("formulaDescriptionList", policy)
                .bind("lists", policy).build();
        //渲染文件
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordDrugTest.docx",config);
        compile.render(data);
        //输出为文件，指定输出文件名
        compile.writeToFile(destFilePath + "out_recordDrugTest.docx");
        compile.close();
    }
}
